<template>
    <el-button color="#0176bb" :icon="Setting" circle @click="showform()"></el-button>
    <el-dialog v-model="FormVisible" :title="formtitle" :width="formwidth">
        <el-row style="padding: 10px">
            <el-col :span="4">
                <el-input v-model="fliterstr" :placeholder="$t('查找')" />
            </el-col>
            <el-col :span="20">
                <!-- <el-button style="float: right" size="default" type="success" @click="Getdata()">
                    刷新<el-icon><RefreshRight /></el-icon>
                </el-button> -->
                <el-button style="float: right" size="default" type="primary" @click="add(0)">
                    {{ $t('新增') }}<el-icon><Plus /></el-icon>
                </el-button>
            </el-col>
        </el-row>
        <el-table :data="filterTableData" border max-height="65vh" highlight-current-row v-loading="loading">
            <el-table-column v-for="(column, index) in tabletitle" header-align="center" :label="I(column.label, column.labeleng)" :prop="column.prop" :width="column.width" :align="column.align" :fixed="column.fixed">
                <template #default="scope">
                    <div v-if="column.prop === 'index'">
                        {{ scope.$index + 1 }}
                    </div>
                    <div v-else-if="column.prop === 'action'">
                        <el-button size="small" type="danger" @click="del(scope.$index)"> {{ $t('删除') }} </el-button>
                        <el-button size="small" type="warning">
                            <el-icon><Rank /></el-icon>
                        </el-button>
                    </div>
                    <div v-else-if="column.prop === 'labelex' || column.prop === 'labeleng' || column.prop === 'prop' || column.prop === 'label'">
                        <el-input v-model="scope.row[column.prop]" />
                    </div>
                    <div v-else-if="column.prop === 'labelex' || column.prop === 'labeleng' || column.prop === 'prop' || column.prop === 'label'">
                        <el-input v-model="scope.row[column.prop]" />
                    </div>
                    <div v-else-if="column.prop === 'type'">
                        <el-select :disabled="scope.row[column.prop] == 'title'" v-model="scope.row[column.prop]" size="default" style="width: 100px">
                            <el-option key="string" :label="$t('字符')" value="string" />
                            <el-option key="number" :label="$t('数字')" value="number" />
                            <el-option key="date" :label="$t('日期')" value="date" />
                            <el-option key="memo" :label="$t('文本')" value="checkbox" />
                            <el-option key="checkbox" :label="$t('选择')" value="checkbox" />
                            <el-option key="action" :label="$t('操作')" value="action" />
                        </el-select>
                    </div>
                    <div v-else-if="column.prop === 'width'">
                        <el-input v-model="scope.row[column.prop]" />
                    </div>
                    <div v-else-if="column.prop === 'align'">
                        <el-radio-group v-model="scope.row[column.prop]">
                            <el-radio value="left1">{{ $t('左') }}</el-radio>
                            <el-radio value="center">{{ $t('中') }}</el-radio>
                            <el-radio value="right">{{ $t('右') }}</el-radio>
                        </el-radio-group>
                    </div>
                    <div v-else-if="column.prop === 'visible' || column.prop === 'readonly' || column.prop === 'isCount' || column.prop === 'isShowSort' || column.prop === 'isShowFilter' || column.prop === 'ismore' || column.prop === 'isRequired'">
                        <el-switch v-model="scope.row[column.prop]" />
                    </div>
                    <div v-else>
                        {{ scope.row[column.prop] }}
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="warning" @click="resetall()">{{ $t('重置系统默认') }}</el-button>
                <el-button @click="cancelhandle()" type="primary" plain>{{ $t('撤销操作') }}</el-button>
                <el-button @click="FormVisible = false" type="primary" plain>{{ $t('取消') }}</el-button>
                <el-button type="primary" @click="save()" v-loading="loading"> {{ $t('保存') }} </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { Setting } from '@element-plus/icons-vue';
import { onMounted, ref, toRefs, computed } from 'vue';
import { httpSend } from '../../utils/api';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { useshareStore } from '@/store'; /*pina管理*/
const { t } = useI18n(); //多语言
let tabletitle: any = [];
interface FormDatabaseProps {
    index?: number;
    type?: number;
    comid?: string;
    Prop?: any;
    isgrant?: boolean;
}
const formdatabase = withDefaults(defineProps<FormDatabaseProps>(), {
    index: 0,
    type: 1,
    comid: null,
    Prop: null,
    isgrant: true
});
const Stores = useshareStore() as any;
const { index, type, comid, Prop } = toRefs(formdatabase);
let Base: any = [];
let tableData: any = ref([]);
//const allcount = tableData.length;
const FormVisible = ref(false);
const loading = ref(false);
//let id = null;
let prokey = { 1: 'tableProps', 2: 'baseProps' };
let formtitle = ref('');
let formwidth = ref(1000);
const fliterstr = ref('');
const emit = defineEmits(['before-click']);
onMounted(() => {});
const filterTableData = computed(() => tableData.value.filter((data) => !fliterstr.value || data.prop.toLowerCase().includes(fliterstr.value.toLowerCase()) || data.label.toUpperCase().includes(fliterstr.value.toUpperCase())));

const handtitle = () => {
    if (type.value == 1) {
        formtitle.value = t('表单自定义配置');
        formwidth.value = 1350;
        tabletitle = [
            { label: '序号', prop: 'index', width: '70', fixed: 'left', type: 'index', align: 'center' },
            { label: '字段编号', prop: 'prop', width: '120', fixed: 'left', align: 'center' },
            { label: '字段类型', prop: 'type', width: '120', fixed: 'left', align: 'center' },
            { label: '字段描述', prop: 'label', width: '120', fixed: 'left', align: 'center' },
            //{ label: '更改描述', prop: 'labelex', width: '120', fixed: 'left', align: 'center' },
            { label: '英文描述', prop: 'labeleng', width: '120', fixed: 'left', align: 'center' },
            { label: '宽度', prop: 'width', width: '120', fixed: null, align: 'center' },
            { label: '对齐方式', prop: 'align', width: '260', fixed: null, align: 'center' },
            { label: '是否显示', prop: 'visible', width: '120', fixed: null, align: 'center' },
            { label: '是否只读', prop: 'readonly', width: '120', fixed: null, align: 'center' },
            { label: '是否统计', prop: 'isCount', width: '120', fixed: null, align: 'center' },
            { label: '是否排序', prop: 'isShowSort', width: '120', fixed: null, align: 'center' },
            { label: '是否过滤', prop: 'isShowFilter', width: '120', fixed: null, align: 'center' },
            { label: '操作', prop: 'action', width: '150', fixed: 'right', align: 'center' },
        ];
    } else if (type.value == 2) {
        formtitle.value = t('表单自定义配置');
        formwidth.value = 1150;
        tabletitle = [
            { label: '序号', prop: 'index', width: '70', fixed: 'left', type: 'index', align: 'center' },
            { label: '字段编号', prop: 'prop', width: '120', fixed: 'left', align: 'center' },
            { label: '字段类型', prop: 'type', width: '120', fixed: 'left', align: 'center' },
            { label: '字段描述', prop: 'label', width: '120', fixed: 'left', align: 'center' },
            // { label: '更改描述', prop: 'labelex', width: '120', fixed: 'left', align: 'center' },
            { label: '英文描述', prop: 'labeleng', width: '120', fixed: 'left', align: 'center' },
            { label: '是否显示', prop: 'visible', width: '120', fixed: null, align: 'center' },
            { label: '是否必填', prop: 'isRequired', width: '120', fixed: null, align: 'center' },
            { label: '是否更多', prop: 'ismore', width: '120', fixed: null, align: 'center' },
            { label: '操作', prop: 'action', width: '150', fixed: 'right', align: 'center' },
        ];
    }
};

const showform = async () => {
    //进行操作前权限检查
    emit('before-click');
    if(!formdatabase.isgrant){
        return;
    }
    loading.value = true;
    FormVisible.value = true;
    setTimeout(() => {
        tableData.value = Stores.comui[comid.value][index.value][prokey[type.value]].map((v) => {
            return { ...v };
        });
        Base = Object.assign(Stores.comui[comid.value]);
        loading.value = false;
    }, 50);
    handtitle();
    //Getdata();
};

//获取数据
// const Getdata = async () => {
//     loading.value = true;
//     const fd = new FormData();
//     let data = { comid: comid.value, userid: null };
//     fd.append('param', JSON.stringify(data));
//     const res = await httpSend('getComUiSet', fd, false);
//     if (res.code == 1) {
//         if (res.data.length > 0) {
//             id = res.data[0]['id'];
//             let data =JSON.parse(res.data[0]['setjson']);
//             tableData.value = data[index.value][prokey[type.value]]
//                 ? data[index.value][prokey[type.value]].map((v) => {
//                       return { ...v };
//                   })
//                 : Prop.value[index.value][prokey[type.value]].map((v) => {
//                       return { ...v };
//                   });
//             Base = JSON.parse(res.data[0]['setjson']);
//         } else {
//             tableData.value = Prop.value[index.value][prokey[type.value]].map((v) => {
//                 return { ...v };
//             });
//             Base = Prop.value.map((v) => {
//                 return { ...v };
//             });
//         }
//     }
//     loading.value = false;
// };

const save = async () => {
    let ispass = false;
    const regex = /^[a-zA-Z0-9_]+$/; //只包含字母、数字或下划线 (_)
    tableData.value.forEach((v, index) => {
        if (v.type != 'title' && !v.prop) {
            ElMessage({ title: t('注意'), message: '[' + (index + 1) + ']' + '行字段编号不能为空', type: 'warning', border: true });
            ispass = true;
            return;
        }
        if (!v.label) {
            ElMessage({ title: t('注意'), message: '[' + (index + 1) + ']' + '行字段描述不能为空', type: 'warning', border: true });
            ispass = true;
            return;
        }
        if (v.type != 'title' && !regex.test(v.prop)) {
            ElMessage({ title: t('注意'), message: '[' + (index + 1) + ']' + '行字段编号不能包含特殊字符', type: 'warning', border: true });
            ispass = true;
            return;
        }
    });
    if (ispass) {
        return;
    }
    loading.value = true;
    const fd = new FormData();
    let savedata = tableData.value.map((v) => {
        return { ...v };
    });
    Base[index.value][prokey[type.value]] = savedata;
    let data = { comid: comid.value, usrid: '', setjson: JSON.stringify(Base) };
    fd.append('param', JSON.stringify(data));
    const res = await httpSend('saveComUiSet', fd);
    if (res.code == 1) {
        fliterstr.value = '';
        let comdata = [];
        comdata[0] = comid.value;
        comdata[1] = [];
        Object.assign(comdata[1], Base);
        Stores.setcomui(comdata);
        FormVisible.value = false;
    }
    loading.value = false;
};

const resetall = () => {
    let data = Prop.value[index.value][prokey[type.value]].map((v) => {
        return { ...v };
    });
    tableData.value = [...data];
};

const cancelhandle = () => {
    let data = Base[index.value][prokey[type.value]].map((v) => {
        return { ...v };
    });
    tableData.value = [...data];
};
//新增
const add = (index) => {
    const newRow = { ...tableData.value[index] };
    newRow.prop = null;
    newRow.label = '';
    newRow.type = '';
    newRow.labeleng = '';
    tableData.value.push(newRow);
};
//删除
const del = (index) => {
    tableData.value.splice(index, 1);
};
const I = (label, labeleng) => {
    if (labeleng && localStorage.getItem('locale') == 'en') {
        return labeleng;
    }
    return t(label);
};
</script>
